import { Injectable } from '@nestjs/common';

import { ConfigService } from '@nestjs/config';
import { ChargeOrderService } from 'src/module/charge-order/charge-order.service';
import { RedisService } from 'src/redis/redis.service';
import { hexToNum, hexToSingle } from 'src/util';

@Injectable()
export class ChargeService {
    private chargeOrderMessageKey:string;
    constructor(private chargeOrderService:ChargeOrderService, private configService:ConfigService, private redis:RedisService) {
        this.chargeOrderMessageKey = this.configService.get<string>('cacheKey.chargeOrderMessage')
        
        this.run()
    }

    run(){
        this.redis.redisClient.brpop(this.chargeOrderMessageKey, 5, (error, result) => {
           if(!result) return
            try {
                if(error == null && result !== null) {
                    const { cmd, data} = JSON.parse(result[1])
                    if(cmd == '0008') { //充电，增加充电，结束充电
                        this.charge(data)
                    }else if(cmd == '0005') { //充电结束，订单上报
                        this.order(data)
                    }
                } 
            } catch (error) {
                
            }

            this.run()
        })
    }

    charge(data:string) {
        const orderId = hexToNum(data.substr(2, 22))
        const chargeAction = hexToNum(data.substr(24, 2))
        const status = hexToNum(data.substr(26, 2))

        if(chargeAction == 1) { //充电
            this.chargeOrderService.chargeNotify(orderId, status)
        }else if(chargeAction == 2) {
            this.chargeOrderService.addChargeNotify(orderId, status)
        }else if(chargeAction == 3) {
            this.chargeOrderService.stopChargeNotify(orderId, status)
        }
    }

    order(data:string) {
        //const portNo = hexToNum(data.substr(0, 2))
        const orderId = hexToNum(data.substr(2, 22))
        const startTime = hexToNum(data.substr(24, 8))
        const endTime = hexToNum(data.substr(32, 8))
        const stopReason = hexToNum(data.substr(40, 2))
        //const strategyType = hexToNum(data.substr(42, 2))
        const consumeEnergy = hexToSingle(data.substr(44, 8))
        const maxPower = hexToSingle(data.substr(52, 8))
        let totalTime = 0
        let times:number[] = []
        times.push(
            hexToNum(data.substr(68, 8)),
            hexToNum(data.substr(76, 8)),
            hexToNum(data.substr(84, 8)),
            hexToNum(data.substr(92, 8))
        )

        times.forEach(t => {
            totalTime += t
        })

        this.chargeOrderService.settlement(orderId, {startTime, endTime, stopReason, consumeEnergy, maxPower, times, totalTime})
    }
}
